package student.aistar.day15.lock;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LockHelloDemo {
    //构建lock对象 - 接口
    Lock lock = new ReentrantLock();

    public void add(){
        try {
            //begin...
            //多个线程就会去竞争"锁资源"
            lock.lock();//手动申请"锁资源" - 显示锁
            //在某个时刻由一个线程进入去执行...
            //同步代码开始
            System.out.println(Thread.currentThread().getName() + ": 0");
            try {
                //sleep如果出现在同步代码块中, 他并不会释放锁资源, 只会让出cpu时间片段
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName()+": 1");

            //end...
            //同步代码结束
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();//手动释放锁
        }
    }

    public static void main(String[] args) {
        LockHelloDemo hello = new LockHelloDemo();
        //1.创建第一个线程对象
        Thread t1 = new Thread(()->{
            hello.add();
        });

        Thread t2 = new Thread(()->{
            hello.add();
        });

        t1.setName("one");
        t2.setName("two");

        t1.start();
        t2.start();

//        Thread t1 = new T1();
//        Thread t2 = new T1();
//
//        t1.start();
//        t2.start();
    }
}
class T1 extends Thread{
    LockHelloDemo helloDemo = new LockHelloDemo();
    @Override
    public void run() {
        helloDemo.add();
    }
}
class T2 extends Thread{
    LockHelloDemo helloDemo = new LockHelloDemo();

    @Override
    public void run() {
        helloDemo.add();
    }
}